package org.jmc.refmanager.domain.service.impl;

import java.util.List;

import javax.annotation.Resource;
import javax.persistence.Query;

import org.jmc.refmanager.domain.dao.AdresseDao;
import org.jmc.refmanager.domain.dao.QueryParam;
import org.jmc.refmanager.domain.model.Adresse;
import org.jmc.refmanager.domain.model.Adresse.AdressePK;
import org.jmc.refmanager.domain.service.AdresseManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service("adresseManager")
@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public class AdresseManagerImpl implements AdresseManager {

	@Resource(name="adresseDao")
	private AdresseDao adresseDao;

	@Override
	public Adresse findByPK(AdressePK pk) {
		return adresseDao.find(pk);
	}

	@Override
	public List<Adresse> list(QueryParam<Adresse> queryParams) {
		if (queryParams.getCriteriaExample() == null || queryParams.getCriteriaExample().getCodePostal() == null) {
			Query query = adresseDao.createQuery("SELECT adr FROM Adresse adr");
			return adresseDao.findAndPaging(setParams(queryParams), query);
		} else {
			Query query = adresseDao.createQuery("SELECT adr FROM Adresse adr WHERE codePostal like ?1");
			String cp = queryParams.getCriteriaExample().getCodePostal();
			return adresseDao.findAndPaging(setParams(queryParams), query, cp.concat("%"));
		}
	}

	@Override
	public Integer count(QueryParam<Adresse> queryParams) {
		if (queryParams.getCriteriaExample() == null || queryParams.getCriteriaExample().getCodePostal() == null) {
			Query query = adresseDao.createQuery("SELECT COUNT(*) FROM Adresse adr");
			return adresseDao.count(query);
		} else {
			Query query = adresseDao.createQuery("SELECT COUNT(*) FROM Adresse adr WHERE codePostal like ?1");
			String cp = queryParams.getCriteriaExample().getCodePostal();
			return adresseDao.count(query, cp.concat("%"));
		}
	}

	private QueryParam<Adresse> setParams(QueryParam<Adresse> queryParams) {
		QueryParam<Adresse> params;
		
		if (queryParams == null) {
			params = new QueryParam<Adresse>();
		} else {
			params = queryParams;
		}
		
		return params;
	}
}
